<template>
	<view class="login_main">
		<view class="return_cancel" @click="cancelLogin" v-if="isLogin">
			<uni-icons type="closeempty" size="26" color="#6b6b6b"></uni-icons>
		</view>
		<view class="login-title-language">
			<view class="login_title">
				登录后更精彩
			</view>
		</view>
		<view class="login_content_main">
			<uni-section title="登录方式" type="circle" title-color="#66596b">
				<view class="select_login_header">
					<uni-segmented-control :current="current" :values="items" :style-type="styleType"
						:active-color="activeColor" @clickItem="onClickItem" />
				</view>
				<view class="login_content">
					<view v-if="current === 0">
						<view class="phone_text_input">
							<view class="phone_text">
								手机号：
							</view>
							<view class="phone_input_view">
								<uni-easyinput type="number" v-model="phoneNumber" placeholder="请输入手机号" clear-size="18"
									trim="true" :inputBorder="false" primary-color="#66596b"></uni-easyinput>
							</view>
						</view>
						<view class="valid_code_text_input phone_text_input">
							<view class="valid_text phone_text">
								验证码：
							</view>
							<view class="valid_input_and_num">
								<view class="valid_input">
									<uni-easyinput type="number" v-model="validCodeNum" placeholder="请输入验证码"
										clear-size="18" trim="true" primary-color="#66596b"
										:inputBorder="false"></uni-easyinput>
								</view>
								<view class="valid_num" @click="getValidCode">
									{{scendNum}}
								</view>
							</view>
						</view>
						<view class="submit_btn_view">
							<button type="default" class="submit_btn" @click="toLogin">登 录</button>
						</view>
					</view>
					<view v-if="current === 1">
						<view class="phone_text_input">
							<view class="phone_text">
								手机号：
							</view>
							<view class="phone_input_view">
								<uni-easyinput class="input-phone" type="number" v-model="phoneWithPassNumber"
									placeholder="请输入手机号" clear-size="18" trim="true" primary-color="#66596b"
									:inputBorder="false"></uni-easyinput>
							</view>
						</view>
						<view class="phone_text_input password_input_view">
							<view class="phone_text">
								密码：
							</view>
							<view class="phone_input_view">
								<uni-easyinput type="password" v-model="userPassword" placeholder="请输入密码"
									clear-size="18" trim="true" primary-color="#66596b"
									:inputBorder="false"></uni-easyinput>
							</view>
						</view>
						<view class="submit_btn_view">
							<button type="default" class="submit_btn" @click="toLogin">登 录</button>
						</view>
					</view>
				</view>
			</uni-section>
			<!-- 其他方式登录 -->
			<uni-section class="other-login" title="其他方式" type="circle" title-color="#66596b">
				<view class="other_login_view">
					<view class="weichat_view">
						<uni-icons type="weixin" size="27" color="#66596b"></uni-icons>
					</view>
					<view class="qq_view">
						<uni-icons type="qq" size="27" color="#66596b"></uni-icons>
					</view>
				</view>
			</uni-section>
		</view>
		<view class="policy_main">
			<view class="checked_view">
				<label class="radio">
					<radio value="agree" :checked="isAgree" @click="changeRadio" color="#66596b" />
				</label>
			</view>
			<view class="policy_text">
				同意
				<text class="policy_text_special">《用户协议》</text>和<text class="policy_text_special">《隐私政策》
				</text>
				，用户首次登录将会同步注册APP账号
			</view>
		</view>
	</view>
</template>


<script>
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex'

	import {
		receptionLoginWithPassword,
		loginByCode
	} from '../../request/login'
	import {
		getCode
	} from '@/request/alioss.js'

	export default {
		data() {
			return {
				isLogin: false, // 是否登录
				phoneNumber: '', // 手机号
				phoneWithPassNumber: '', // 密码登录的手机号
				current: 0, // 当前登录方式的索引
				items: ['验证码', '密码'], // 登录方式
				styleType: 'text',
				activeColor: '#66596b',
				scendNum: '获取验证码', // 倒数60秒
				validCodeNum: null, // 验证码
				userPassword: '', // 密码
				isAgree: false, // 是否勾选同意隐私协议
				countDownInterval: null,
				code: null, // 后端返回来的验证码
				isCountingDown: false, // 新增：是否正在倒计时
			}
		},

		computed: {
			...mapState(['hasLogin']),

		},

		onLoad() {
			// 判断是否登录了
			this.checkIsLogin();

		},


		beforeDestroy() {
			if (this.countDownInterval) {
				clearInterval(this.countDownInterval)
			}
		},

		methods: {

			// 判断是否登录了
			checkIsLogin() {
				if (uni.getStorageSync("isLogin") === "") {
					this.isLogin = false;
				} else {
					this.isLogin = true;
				}
			},

			// 取消登录返回上一页
			cancelLogin() {
				uni.navigateBack();
			},
			// 点击更换登录方式
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
			},
			// 发送验证码
			getValidCode() {
				const self = this;
				if (self.validatePhoneNumber()) {
					if (!self.isCountingDown) {
						uni.showToast({
							title: '请注意查看手机短信,请耐心等待...',
							icon: 'none'
						})
						this.isCountingDown = true; // 开始倒计时，设置为 true
						this.scendNum = '60' + '秒';
						let secondNumInt = Number(self.scendNum.slice(0, -1));
						const data = {
							phone: self.phoneNumber
						}
						getCode(data).then(res => {
							// console.log(res);
							self.code = res.data.data;
							// console.log("后端传过来的验证码为：",self.code);
						}).catch(err => {
							console.log(err);
							uni.showToast({
								title: '验证码获取失败！请用其他方式登录',
								icon: 'none'
							})
						})
						self.countDownInterval = setInterval(() => {
							secondNumInt--;
							self.scendNum = String(secondNumInt) + ' s';
							if (secondNumInt === 0) {
								clearInterval(self.countDownInterval);
								self.scendNum = "获取验证码";
								this.isCountingDown = false; // 倒计时结束，恢复可点击状态
							}
						}, 1000);
					}else{
						uni.showToast({
							title: '请在倒计时结束之后再获取验证码',
							icon: 'none'
						})
					}
				}
			},
			validatePhoneNumber() {
				// 定义手机号正则表达式
				const phoneRegex = /^1[3-9]\d{9}$/;
				// 判断当前选择的登录方式
				if (this.current === 0) {
					if (this.phoneNumber === '') {
						uni.showToast({
							title: "请先输入手机号！",
							icon: 'none'
						})
						return false;
					} else {
						if (!phoneRegex.test(this.phoneNumber)) {
							uni.showToast({
								title: '手机号格式不正确！',
								icon: 'none'
							});
							return false;
						} else {
							return true;
						}
					}
				} else if (this.current === 1) {
					if (this.phoneWithPassNumber === '') {
						uni.showToast({
							title: '请先输入手机号！',
							icon: 'none'
						})
						return false;
					} else {
						if (!phoneRegex.test(this.phoneWithPassNumber)) {
							uni.showToast({
								title: '手机号格式不正确！',
								icon: 'error'
							});
							return false;
						} else {
							return true;
						}
					}
				}
			},

			// 点击登录
			toLogin() {
				const _this = this;
				if (_this.validatePhoneNumber()) {
					if (_this.current === 0) {
						if (_this.validCodeNum === '') {
							uni.showToast({
								title: '请先输入验证码！',
								icon: 'none',
							})
							return;
						} else {
							if (_this.isAgree === false) {
								uni.showToast({
									title: '请阅读并勾选用户协议和隐私政策',
									icon: 'none',
								})
								return;
							} else {
								// 后端验证手机号发来的验证码是否正确
								if(_this.code != _this.validCodeNum){
									uni.showToast({
										title: '验证码不正确',
										icon: 'none',
									})
									return;
								}
								// 发送到后端，如果用户表中有这个手机号，就登陆成功；如果用户表中没有这个手机号，就注册成功，也代表登录成功
								const loginByCodeParam = {
									phone: _this.phoneNumber
								}
								loginByCode(loginByCodeParam).then(res=>{
									// console.log(res);
									uni.setStorageSync("isLogin", true);
									uni.setStorageSync("token", res.data.data);
									uni.switchTab({
										url: '/pages/tabBar/template/template'
									})
								})
							}
						}
					} else {
						if (this.userPassword === '') {
							uni.showToast({
								title: '请输入密码！',
								icon: 'error',
							})
						} else {
							if (this.isAgree === false) {
								uni.showModal({
									title: '提示', //标题
									content: '请阅读并勾选用户协议和隐私政策', //提示内容
									showCancel: false, //不显示取消按钮
									confirmText: '好的'
								})
							} else {
								// 后端验证手机号，是否注册过，如果注册过，查询密码验证密码是否正确
								const params = {
									phone: this.phoneWithPassNumber,
									password: this.userPassword,
								}
								receptionLoginWithPassword(params).then(res => {
									if (res.data.code === 10000 && res.data.message === '登陆成功！') {
										// 获取token
										// console.log(res.data.data.token);
										uni.setStorageSync("isLogin", true);
										uni.setStorageSync("token", res.data.data.token);
										uni.switchTab({
											url: '/pages/tabBar/template/template'
										})
										uni.showToast({
											title: res.data.message,
										})
									} else if (res.data.code === 10001 && res.data.message === '手机号不存在') {
										uni.showModal({
											title: '提示', //标题
											content: '手机号还未注册，请先去注册！', //提示内容
											showCancel: false, //不显示取消按钮
											confirmText: '好的'
										})
									} else if (res.data.code === 10001 && res.data.message === "密码错误！") {
										uni.showToast({
											title: '密码错误',
											icon: 'error'
										})
									} else {

									}
								}).catch(err => {
									console.log(err);
									uni.showToast({
										title: '登录失败！请稍后再试...',
										icon: 'error'
									})
								})
							}
						}
					}
				}
			},

			// 改变勾选状态
			changeRadio() {
				this.isAgree = !this.isAgree;
			},
		}
	}
</script>

<style scoped>
	.login_main {
		padding: 30rpx;
		padding-top: 60rpx;
	}

	.login-title-language {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.login_title {
		font-size: 50rpx;
	}

	.login_content_main {
		margin-top: 30rpx;
		padding-bottom: 50rpx;
	}

	.login_content {
		margin-top: 30rpx;
		padding: 30rpx;
		margin-bottom: 50rpx;
	}

	.content-text-section {
		font-size: 30rpx;
	}

	.phone_text_input {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between
	}

	.phone_text {
		font-size: 30rpx;
	}

	.phone_input_view {
		padding-top: 7rpx;
		height: 70rpx;
		width: 70%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		border-radius: 14rpx;
		align-items: center;
		background-color: #ffffff;
		padding-left: 20rpx;
	}


	.valid_input_and_num {
		background-color: #ffffff;
		height: 76rpx;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		border-radius: 14rpx;
		padding-left: 20rpx;
		width: 70%;
		align-items: center;
	}

	.valid_code_text_input {
		margin-top: 40rpx;
	}

	.valid_input {
		width: 50%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.valid_num {
		width: 40%;
		height: 76rpx;
		background-color: #66596b;
		font-size: 28rpx;
		color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;
		border-top-right-radius: 14rpx;
		border-bottom-right-radius: 14rpx;
	}

	.submit_btn_view {
		margin-top: 120rpx;
	}

	.submit_btn_view button {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		letter-spacing: 20rpx;
		color: #fff;
		background-color: #66596b;
		box-shadow: 3px 3px 5px 1px rgba(197, 197, 197, 0.3);
		border-radius: 50rpx;
	}

	.password_input_view {
		margin-top: 40rpx;
	}

	.other_login_view {
		display: flex;
		flex-direction: row;
		padding: 30rpx;
	}

	.weichat_view {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		border: 1px solid;
		border-color: #cccccc;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 30rpx;
	}

	.qq_view {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		border: 1px solid;
		border-color: #cccccc;
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.policy_main {
		position: absolute;
		bottom: 30rpx;
		left: 0;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		font-size: 24rpx;
		padding: 30rpx;
	}

	.policy_text_special {
		color: #95c3ff;
	}

	.other-login {
		margin-top: 30rpx;
	}
</style>